package com.health.idcard.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.health.R;
import com.health.idcard.entity.MyIdCardBean;
import com.huashi.otg.sdk.HSIDCardInfo;
import com.huashi.otg.sdk.HSLOG;
import com.huashi.otg.sdk.HandlerMsg;
import com.huashi.otg.sdk.HsOtgApi;

import java.text.SimpleDateFormat;

public class USBIdCardService extends Service {

    private static final String TAG = "USBIdCardService";

    HsOtgApi hsOtgApi = null;
    boolean m_Con = false;
    boolean m_Auto = false;
    long startTime;
    int m_ReadIDCardSUCCESS = 0;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
    private String idCard = "";
    private MediaPlayer mediaPlayer;

    public USBIdCardService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        initUsbCard();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * usb读卡器初始化 连接
     */
    private void initUsbCard() {
        if (hsOtgApi == null) {
            hsOtgApi = new HsOtgApi(handler, this);
        }
        int ret = hsOtgApi.init();// 因为第一次需要点击授权，第一次点击时候的返回是-1,我利用了广播接受到授权后用handler发送消息
        HSLOG.m_Addlog = false;
        if (ret == 1) {
            Log.e(TAG, "连接成功,模块号：" + hsOtgApi.GetSAMID());
            m_Con = true;
            readCard();
        } else {
            ToastUtils.showShort("usb读卡器连接失败");
            m_Con = false;
        }
    }



    /**
     * 播放读取成功音频
     */
    private void showMediaPlayer() {
        mediaPlayer = MediaPlayer.create(this, R.raw.read_card_success);
        mediaPlayer.start();
    }

    private void release() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            release();
            if (m_Auto) {
                m_Auto = false;
                SystemClock.sleep(1500);
            }
            if (hsOtgApi != null) {
                hsOtgApi.unInit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void readCard() {
        if (!m_Con) {
            ToastUtils.showShort("usb读卡器未连接");
            return;
        }
        if (m_Auto) {
            m_Auto = false;
//            autoread.setText("自动读卡");
        } else {
            m_Auto = true;
            new Thread(new CPUThread()).start();
            m_ReadIDCardSUCCESS = 0;
//            autoread.setText("停止读卡");
        }
    }

    public class CPUThread extends Thread {
        public CPUThread() {
            super();
        }

        @Override
        public void run() {
            super.run();
            HSIDCardInfo ici;
            Message msg;
            while (m_Auto) {
                // ///////////////循环读卡，不拿开身份证
                if (hsOtgApi.NotAuthenticate(200, 200) == 1) {
                    // ////////////////循环读卡，需要重新拿开身份证
//                if (hsOtgApi.Authenticate(200, 200) == 1) {
                    ici = new HSIDCardInfo();
                    if (hsOtgApi.ReadCard(ici, 200, 1300) == 1) {
                        msg = Message.obtain();
                        msg.obj = ici;
                        msg.what = HandlerMsg.READ_SUCCESS;
                        handler.sendMessage(msg);
                    } else {
                        // 读卡失败
                        msg = Message.obtain();
                        msg.what = HandlerMsg.READ_ERROR;
                        handler.sendMessage(msg);
                        SystemClock.sleep(300);
                    }
                } else {
                    // 卡认证失败
                    msg = Message.obtain();
                    msg.what = HandlerMsg.READ_ERROR;
                    handler.sendMessage(msg);
                    SystemClock.sleep(300);
                }
            }
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 99 || msg.what == 100) {
                Log.e(TAG, "handleMessage: " + (String) msg.obj );
                m_Con = false;
            }
            // 第一次授权时候的判断是利用handler判断，授权过后就不用这个判断了
            if (msg.what == HandlerMsg.CONNECT_SUCCESS) {
                Log.e(TAG, "连接成功" + hsOtgApi.GetSAMID());
                m_Con = true;
                //sam.setText(api.GetSAMID());
            }
            if (msg.what == HandlerMsg.CONNECT_ERROR) {
                Log.e(TAG, "连接失败" );
            }
            if (msg.what == HandlerMsg.READ_ERROR) {
                Log.e(TAG, "请放卡..." );
            }
            if (msg.what == HandlerMsg.READ_SUCCESS) {
                HSIDCardInfo ic = (HSIDCardInfo) msg.obj;
                byte[] fp = new byte[1024];
                fp = ic.getFpDate();
                String m_FristPFInfo = "";
                String m_SecondPFInfo = "";

                if (fp[4] == (byte) 0x01) {
                    m_FristPFInfo = String.format(
                            "指纹  信息：第一枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[5]), fp[6]);
                } else {
                    m_FristPFInfo = "身份证无指纹 \n";
                }
                if (fp[512 + 4] == (byte) 0x01) {
                    m_SecondPFInfo = String.format(
                            "指纹  信息：第二枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[512 + 5]), fp[512 + 6]);
                } else {
                    m_SecondPFInfo = "身份证无指纹 \n";
                }
                if (ic.getcertType() == " ") {
                    MyIdCardBean myIdCardBean = new MyIdCardBean();
                    myIdCardBean.setIdCard(ic.getIDCard());
                    myIdCardBean.setName(ic.getPeopleName());
                    myIdCardBean.setSex(ic.getSex());
                    myIdCardBean.setNation(ic.getPeople());
                    myIdCardBean.setBirthday(df.format(ic.getBirthDay()));
                    myIdCardBean.setAddress(ic.getAddr());
                    nextActivityUsb(myIdCardBean);
                } else {
                    if (ic.getcertType() == "J") {
                    } else {
                        if (ic.getcertType() == "I") {
                        }  else {
                        }
                    }

                }
                try {
                    //////////////////////////////////////////////////////////////////////////////////////
                    if (!m_Auto) {
                        startTime = System.currentTimeMillis() - startTime;
//                        statu.setText("读卡成功,用时：" + startTime);
                    }
                    else{
//                        statu.setText("读卡成功");
                        m_ReadIDCardSUCCESS++;
//                        tv_Log.setText("成功次数:" + m_ReadIDCardSUCCESS);
                    }
                } catch (Exception e) {
//                    Toast.makeText(getApplicationContext(), "头像解码失败",
//                            Toast.LENGTH_SHORT).show();
                }

            }
        };
    };

    private void nextActivityUsb(MyIdCardBean myIdCardBean) {
        if (!idCard.equals(myIdCardBean.getIdCard())) {
            idCard = myIdCardBean.getIdCard();
            //显示身份证数据
            showMediaPlayer();
//            SScardInfo sScardInfo = new SScardInfo(
//                    "",
//                    myIdCardBean.getIdCard(),
//                    myIdCardBean.getAddress(),
//                    "",
//                    myIdCardBean.getName(),
//                    "",
//                    "",
//                    "",
//                    "",
//                    ""
//            );
//            BusUtils.post("yb_card_tag", myIdCardBean);

            Intent intent = new Intent("com.idcard.data");
            intent.putExtra("idcard_data", myIdCardBean);
            sendBroadcast(intent);
            // 15秒钟清空下， 防止再次刷卡无效
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    idCard = "";
                }
            }, 15 * 1000);
        }
    }

    /**
     * 指纹 指位代码
     *
     * @param FPcode
     * @return
     */
    String GetFPcode(int FPcode) {
        switch (FPcode) {
            case 11:
                return "右手拇指";
            case 12:
                return "右手食指";
            case 13:
                return "右手中指";
            case 14:
                return "右手环指";
            case 15:
                return "右手小指";
            case 16:
                return "左手拇指";
            case 17:
                return "左手食指";
            case 18:
                return "左手中指";
            case 19:
                return "左手环指";
            case 20:
                return "左手小指";
            case 97:
                return "右手不确定指位";
            case 98:
                return "左手不确定指位";
            case 99:
                return "其他不确定指位";
            default:
                return "未知";
        }
    }

}
